/*
 * Dit is de Client. Hiermee kun je verbdinging maken met een Chat server.
 * Deze Client Server werkt in de commanldline en leest uit de stdin.
 * Gebruik: java Client Hostname Port
 *
 */

// ow150.science.uva.nl 16897
import java.io.*;

import java.net.*;

 

public class Client{
    public static String SERVER_HOSTNAME = "ow150.science.uva.nl";
    public static int SERVER_PORT = 16897;
    private static int majorVersion = 1;
    private static int minorVersion = 0;
    public String version =  majorVersion + "." + minorVersion;

    public static void main(String[] args)

    {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
           // Connect to Nakov Chat Server
           Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
           in = new BufferedReader(
               new InputStreamReader(socket.getInputStream()));
           out = new PrintWriter(
               new OutputStreamWriter(socket.getOutputStream()));
           SERVER_HOSTNAME = args[0];
           SERVER_PORT = Integer.parseInt(args[1]);
           System.out.println("Connected to server " +
              SERVER_HOSTNAME + ":" + SERVER_PORT);
        } catch (IOException ioe) {
           System.err.println("Can not establish connection to " +
               SERVER_HOSTNAME + ":" + SERVER_PORT);
           ioe.printStackTrace();
           System.exit(-1);
        }
         /*
          * The chat
          */

        // Create and start Sender thread
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        Sender sender = new Sender(out);
        sender.setDaemon(true);
        String message;
        try{
            message = in.readLine();
            System.out.println(message);
            /*
             * Check if the server has the same version as the client.
             */
            if(!versionChecker(message))
                throw new IOException();
            /*
             * Send CHAT to the server to complete the first step of the client.
             */
            out.print("CHAT\r\n");
            out.flush();
            message = in.readLine();
            System.out.println(message);
			
            while(!(message.startsWith("+"))){
                 System.out.println(message);
                 throw new IOException();
            }
            /*
             * Start Username protocol
             */
            do{
                //message = in.readLine();
                //System.out.println(message);
                System.out.println("Give Username\n");
                message = input.readLine();
                out.print("USER " + message + "\r\n");
                out.flush();
                message = in.readLine();
                if((message.startsWith("+")))
                    break;
                message = message.substring(2);
                System.out.println(message);
            } while(!(message.startsWith("+")));
            sender.start();
            // Read messages from the server and print them
            while((message=in.readLine()) != null) {
                System.out.println(message);
            }
        } catch (IOException ioe) {
            System.err.println("Connection to server broken.");
            ioe.printStackTrace();
        }
    }

    /*
     * Method for comparing the versions of the server and the client.
     * If the minorVersion is different its up to the user if he wants to
     * continue. If the majorVersion is different it will stop.
     */
    private static boolean versionChecker(String welcomeMessage){
        String[] message = welcomeMessage.split("/");
        String[] versions = message[1].split("\\.");
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        if(Integer.parseInt(versions[0]) == majorVersion){
            if(Integer.parseInt(versions[1]) != minorVersion){
                while(true){
                    System.out.println("Minor version doesn't match "
                            + "do you want to continue: y/n");
                    try{
                        String input = read.readLine();
                        if(input.matches("y")){
                            return true;
                        }
                        else if(input.matches("n")){
                            return false;
                        }
                        else {
                            System.out.println("invalid input");
                        }
                    }
                    catch (IOException ioe) {
                    System.err.println("Connection to server broken.");
                    ioe.printStackTrace();
                    }
                }
            }
        }
        else{
            System.out.println("Version incompatible with the server");
            return false;
        }
        return true;
    }
}

class Sender extends Thread
{
    private PrintWriter mOut;
	public Sender(PrintWriter aOut){
            mOut = aOut;
	}
        /**
         * Until interrupted reads messages from the standard input (keyboard)
         * and sends them to the chat server through the socket.
         */
	public void run()
	{
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (!isInterrupted()) {
                String message = in.readLine();
                if(message.matches("NAMES")){
                    mOut.print(message + "\r\n");
                    mOut.flush();
                }
                else if(message.matches("HELP"))
                {
                    mOut.print(message + "\r\n");
                    mOut.flush();
                }
                else if(message.startsWith("RENAME ")){
                    message = message.substring(7);
					mOut.print("USER "+ message + "\r\n");
                    mOut.flush();
                }
                else {
                    message = "SAY" + " " + message + "\r\n";
                    mOut.print(message);
                    mOut.flush();
                }
            }
        } catch (IOException ioe) {
                   // Communication is broken
        }
	}
}



 

